const axios = require('axios');
const logger = require('../utils/logger');

class ExternalApiService {
  constructor() {
    this.defaultConfig = {
      timeout: 10000,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
        'Content-Type': 'application/json'
      }
    };
  }

  /**
   * 发送GET请求到外部API
   * @param {string} url - 请求URL
   * @param {object} config - 请求配置
   * @returns {Promise} 响应数据
   */
  async get(url, config = {}) {
    try {
      const response = await axios.get(url, {
        ...this.defaultConfig,
        ...config
      });
      
      logger.info(`外部API GET请求成功: ${url}`);
      return response.data;
    } catch (error) {
      logger.error(`外部API GET请求失败: ${url}`, {
        error: error.message,
        status: error.response?.status,
        data: error.response?.data
      });
      throw error;
    }
  }

  /**
   * 发送POST请求到外部API
   * @param {string} url - 请求URL
   * @param {object} data - 请求数据
   * @param {object} config - 请求配置
   * @returns {Promise} 响应数据
   */
  async post(url, data = {}, config = {}) {
    try {
      const response = await axios.post(url, data, {
        ...this.defaultConfig,
        ...config
      });
      
      logger.info(`外部API POST请求成功: ${url}`);
      return response.data;
    } catch (error) {
      logger.error(`外部API POST请求失败: ${url}`, {
        error: error.message,
        status: error.response?.status,
        data: error.response?.data
      });
      throw error;
    }
  }

  /**
   * 发送PUT请求到外部API
   * @param {string} url - 请求URL
   * @param {object} data - 请求数据
   * @param {object} config - 请求配置
   * @returns {Promise} 响应数据
   */
  async put(url, data = {}, config = {}) {
    try {
      const response = await axios.put(url, data, {
        ...this.defaultConfig,
        ...config
      });
      
      logger.info(`外部API PUT请求成功: ${url}`);
      return response.data;
    } catch (error) {
      logger.error(`外部API PUT请求失败: ${url}`, {
        error: error.message,
        status: error.response?.status,
        data: error.response?.data
      });
      throw error;
    }
  }

  /**
   * 发送DELETE请求到外部API
   * @param {string} url - 请求URL
   * @param {object} config - 请求配置
   * @returns {Promise} 响应数据
   */
  async delete(url, config = {}) {
    try {
      const response = await axios.delete(url, {
        ...this.defaultConfig,
        ...config
      });
      
      logger.info(`外部API DELETE请求成功: ${url}`);
      return response.data;
    } catch (error) {
      logger.error(`外部API DELETE请求失败: ${url}`, {
        error: error.message,
        status: error.response?.status,
        data: error.response?.data
      });
      throw error;
    }
  }

  /**
   * 批量请求处理
   * @param {Array} requests - 请求配置数组
   * @returns {Promise<Array>} 响应结果数组
   */
  async batch(requests) {
    try {
      const promises = requests.map(req => {
        const { method, url, data, config } = req;
        switch (method.toLowerCase()) {
          case 'get':
            return this.get(url, config);
          case 'post':
            return this.post(url, data, config);
          case 'put':
            return this.put(url, data, config);
          case 'delete':
            return this.delete(url, config);
          default:
            throw new Error(`不支持的HTTP方法: ${method}`);
        }
      });

      const results = await Promise.allSettled(promises);
      logger.info(`批量请求完成，共${requests.length}个请求`);
      
      return results.map((result, index) => ({
        index,
        url: requests[index].url,
        success: result.status === 'fulfilled',
        data: result.status === 'fulfilled' ? result.value : result.reason
      }));
    } catch (error) {
      logger.error('批量请求处理失败', { error: error.message });
      throw error;
    }
  }
}

module.exports = new ExternalApiService();
